﻿Imports System.Data
Imports CrystalDecisions.Shared
Imports CrystalDecisions.CrystalReports.Engine
Imports System.Data.OleDb
Imports System
Imports System.Globalization

Partial Class Interfaz_frmAdminRequisicion
    Inherits System.Web.UI.Page
    Dim CL As New ControladorLogica
    Dim dtDatos As New DataTable
    Dim dataset As New DataSet

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        If CL.visibilidadesFormsInternos("Administracion", Session("user").ToString) = False Then
            Response.Redirect("Index.aspx")
        End If
        Dim i As Integer
        Dim ArrayProveedor As New ArrayList
        Dim ArrayFamilia As New ArrayList
        Dim ArrayMaterial As New ArrayList

        ArrayProveedor = CL.ObtenerProveedor()
        ArrayFamilia = CL.ObtenerFamilia()
        ArrayMaterial = CL.ObtenerMaterial()

        If Not Page.IsPostBack Then
            Me.DropProveedor.Items.Add("-----")
            For i = 0 To ArrayProveedor.Count - 1
                Dim item As New ListItem
                item.Text = DirectCast(ArrayProveedor.Item(i), Proveedor).Rznsocial
                item.Value = DirectCast(ArrayProveedor.Item(i), Proveedor).Rut
                Me.DropProveedor.Items.Add(item)
            Next
            For i = 0 To ArrayFamilia.Count - 1
                Me.DropFamilias.Items.Add(DirectCast(ArrayFamilia.Item(i), Familia).Nombre)
            Next

            For i = 0 To ArrayMaterial.Count - 1
                Me.DropCodigoMateriales.Items.Add(DirectCast(ArrayMaterial.Item(i), Material).Codigo)
            Next
        End If

        'se guardan datos en secion para el positback de la pagina respecto al los datos del datagridview
        If Session("Requisicion") Is Nothing Then
            Session("Requisicion") = dtDatos
        Else
            dtDatos = DirectCast(Session("Requisicion"), DataTable)

        End If

        If Not Page.IsPostBack Then
            Try
                dtDatos.Columns.Add(New DataColumn("ITEM"))
                dtDatos.Columns.Add(New DataColumn("UNIDAD"))
                dtDatos.Columns.Add(New DataColumn("DETALLE"))
                dtDatos.Columns.Add(New DataColumn("CANTIDAD"))
                dtDatos.Columns.Add(New DataColumn("PRECIOUNITARIO"))
                dtDatos.Columns.Add(New DataColumn("CODMATERIAL"))
                dtDatos.Columns.Add(New DataColumn("PROVEEDOR"))

                Me.GridRequisicion.DataBind()
                Me.GridRequisicion.DataSource = Me.dtDatos

            Catch
            End Try
        End If
        ' Me.GridRequisicion.DataBind()
        Me.GridRequisicion.DataSource = Me.dtDatos
    End Sub

#Region "Funcionalidades"
    Public Sub Mensaje(ByVal msg As String)
        Dim alertScript As String = "<script language=JavaScript runat=server>"
        alertScript &= "alert('" & msg & "');"
        alertScript &= "</script>"
        ClientScript.RegisterClientScriptBlock(Page.GetType(), "clientScrip", alertScript)
    End Sub

    Private Sub InsertarRequisicion()
        Try
            Dim drDatos As DataRow = dtDatos.NewRow

            If Me.TxtUnidad.Text <> "" And Me.TxtDescripcion.Text <> _
            "" And Me.TxtCantidad.Text <> "" And Me.TxtUM.Text <> "" _
            And Me.TxtPrecioUnit.Text <> "" Then

                drDatos.Item("ITEM") = Me.DropMaterial.Text
                drDatos.Item("UNIDAD") = Me.TxtUnidad.Text
                drDatos.Item("DETALLE") = Me.TxtDescripcion.Text
                drDatos.Item("CANTIDAD") = Me.TxtCantidad.Text
                drDatos.Item("PRECIOUNITARIO") = CInt(Me.TxtPrecioUnit.Text)
                drDatos.Item("CODMATERIAL") = DirectCast(CL.ObtenerMaterialNombre(DropMaterial.Text).Item(0), Material).Codigo
                drDatos.Item("PROVEEDOR") = Me.DropProveedor.SelectedValue

                dtDatos.Rows.Add(drDatos)

                Me.GridRequisicion.DataSource = dtDatos
                Me.GridRequisicion.DataBind()

                Me.LimpiarItem()
                Me.GridRequisicion.ForeColor = Drawing.Color.Blue
                Me.LabelAviso.Text = "Los datos han sido ingresados satisfactoriamente"
            Else
                Me.LabelAviso.ForeColor = Drawing.Color.Red
                Me.LabelAviso.Text = "Complete todos los datos"
            End If

        Catch ex As Exception
            Me.Mensaje(ex.ToString)
        End Try
    End Sub

    Private Sub LimpiarItem()
        TxtUM.Text = String.Empty
        TxtPrecioUnit.Text = String.Empty
        TxtCantidad.Text = String.Empty
        TxtDescripcion.Text = String.Empty
        Me.TxtUnidad.Text = String.Empty
    End Sub

    Private Sub IngresarRequisicionBD()
        Dim filaGrid As GridViewRow

        'Datos Fijos
        Dim proveedor As Proveedor = DirectCast(CL.ObtenerProveedorID(DropProveedor.SelectedValue).Item(0), Proveedor)
        Dim Fecha As String = BasicDatePicker1.Text
        Dim dia As String = Fecha.Substring(0, 2)
        Dim mes As String = Fecha.Substring(3, 2)
        Dim año As String = Fecha.Substring(6, 4)

        'Declaraciones para item de la requisicion
        Dim ReqItem As String
        Dim ReqUnidad As String
        Dim ReqDetalle As String
        Dim ReqCantidad As String
        Dim ReqPrecioUnitario As String
        Dim ReqCodigo As String
        Dim ReqProveedor As String
        Dim TotalPorItem As Integer
        Dim TotalNeto As Integer
        Dim iva As Integer
        Dim totalBruto As Integer
        Dim cantidad As Integer

        'Declaraciones para insert a BD
        Dim ArrayItemRequisicion As New ArrayList

        Try
            'Suma Valores de actividades
            With Me.GridRequisicion
                ' Recorrer las filas del dataGridView  
                For fila As Integer = 0 To .Rows.Count - 1
                    filaGrid = Me.GridRequisicion.Rows(fila)

                    'Recorrer la cantidad de columnas que contiene el dataGridView  
                    ReqItem = filaGrid.Cells(1).Text
                    ReqUnidad = filaGrid.Cells(2).Text
                    ReqDetalle = filaGrid.Cells(3).Text
                    ReqCantidad = filaGrid.Cells(4).Text
                    ReqPrecioUnitario = filaGrid.Cells(5).Text
                    ReqCodigo = filaGrid.Cells(6).Text
                    ReqProveedor = DirectCast(CL.ObtenerProveedorID(filaGrid.Cells(7).Text).Item(0), Proveedor).Rut

                    TotalPorItem = CInt(filaGrid.Cells(4).Text) * CInt(filaGrid.Cells(5).Text)
                    TotalNeto = TotalNeto + TotalPorItem
                    cantidad = cantidad + ReqCantidad

                    Dim itemRequisicion As New Item(ReqCodigo, ReqDetalle, ReqCantidad, ReqPrecioUnitario, _
                                                ReqItem, TotalPorItem * 0.19, TotalPorItem)
                    itemRequisicion.FKPROVEEDOR = ReqProveedor
                    ArrayItemRequisicion.Add(itemRequisicion)
                Next fila
            End With


            'Calculo Valores Neto - Bruto - Iva
            iva = TotalNeto * 0.19
            totalBruto = TotalNeto + iva

            'Creacion factura e Ingreso a la BD
            Dim Prioridad As String = ""

            If Me.CkProg3.Checked = True Then
                Prioridad = "Alta (1-2 Dias)"
            Else
                If Me.CkProg2.Checked = True Then
                    Prioridad = "Programada (" + TxTProgramada.Text + ")"
                Else
                    If Me.CkProg.Checked = True Then
                        Prioridad = "Normal (1 semana)"
                    End If
                End If
            End If

            Dim nuevaRequisicion As New Requisicion(0, Prioridad, TxtUnidad.Text, TotalNeto, cantidad, TxtUM.Text, TxTNota.Text)
            nuevaRequisicion.ArrayItem = ArrayItemRequisicion

            CL.insertarRequisicion(nuevaRequisicion)
        Catch ex As Exception
            Me.Mensaje(ex.ToString)
        End Try

    End Sub

    Private Sub vaciaGrid()
        dtDatos = DirectCast(Session("Requisicion"), DataTable)
        If Not dtDatos Is Nothing Then
            dtDatos.Clear()
            Session("Requisicion") = dtDatos
        End If
        Me.GridRequisicion.DataSource = Nothing
        Me.GridRequisicion.DataBind()
    End Sub

    Public Sub BuscarItemFamilia()
        Dim query As String = "select id from familiamateriales where nombre='" + Me.DropFamilias.Text + "'"
        Dim refFamilia As String = CL.Ejecuta(query).Item("id").ToString
        query = "select * from material where reffamilia = " + refFamilia
        Dim arrayMaterial As ArrayList = CL.ObtenerMaterial(query)

        Me.DropMaterial.Items.Clear()
        If arrayMaterial.Count <> 0 Then
            For i As Integer = 0 To arrayMaterial.Count - 1
                Dim item As Material = DirectCast(arrayMaterial.Item(0), Material)
                Me.DropMaterial.Items.Add(item.Nombre)
            Next
        Else
            Me.Mensaje("No hay materiales asociados a la familia seleccionada")
        End If

    End Sub
#End Region

#Region "Botones"

    Protected Sub Button3_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button3.Click
        Me.LimpiarItem()
    End Sub

    Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
        InsertarRequisicion()
    End Sub

    Protected Sub BtnValidar_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles BtnValidar.Click
        IngresarRequisicionBD()
        Me.vaciaGrid()
    End Sub

    Protected Sub BtnBuscar_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles BtnBuscar.Click
        BuscarItemFamilia()
    End Sub
#End Region

#Region "Eventos Grid"
    'Grid Material
    Protected Sub GridRequisicion_PageIndexChanging(ByVal sender As Object, ByVal e As GridViewPageEventArgs)
        GridRequisicion.PageIndex = e.NewPageIndex
        'Bind data to the GridView control.
        GridRequisicion.DataSource = Session("Requisicion")
        GridRequisicion.DataBind()
    End Sub

    Protected Sub GridRequisicion_RowEditing(ByVal sender As Object, ByVal e As GridViewEditEventArgs)
        'Set the edit index.
        GridRequisicion.EditIndex = e.NewEditIndex
        'Bind data to the GridView control.
        GridRequisicion.DataSource = Session("Requisicion")
        GridRequisicion.DataBind()
    End Sub

    Protected Sub GridRequisicion_RowCancelingEdit(ByVal sender As Object, ByVal e As GridViewCancelEditEventArgs)
        'Reset the edit index.
        GridRequisicion.EditIndex = -1
        'Bind data to the GridView control.
        GridRequisicion.DataSource = Session("Requisicion")
        GridRequisicion.DataBind()
    End Sub

    Protected Sub GridRequisicion_RowUpdating(ByVal sender As Object, ByVal e As GridViewUpdateEventArgs)
        'Retrieve the table from the session object.
        Dim dt As DataTable = CType(Session("Requisicion"), DataTable)

        'Update the values.
        Dim row As GridViewRow = GridRequisicion.Rows(e.RowIndex)
        'Dim actividad As String = (CType((row.Cells(2).Controls(0)), TextBox)).Text.ToString
        Dim CODIGO As String = (CType((row.Cells(2).Controls(0)), TextBox)).Text
        Dim DETALLE As String = (CType((row.Cells(3).Controls(0)), TextBox)).Text
        Dim CANTIDAD As String = (CType((row.Cells(4).Controls(0)), TextBox)).Text
        Dim PRECIOUNITARIO As String = (CType((row.Cells(5).Controls(0)), TextBox)).Text

        'dt.Rows(row.DataItemIndex)("ITEM") = actividad
        dt.Rows(row.DataItemIndex)("CODIGO") = CODIGO
        dt.Rows(row.DataItemIndex)("DETALLE") = DETALLE
        dt.Rows(row.DataItemIndex)("CANTIDAD") = CANTIDAD
        dt.Rows(row.DataItemIndex)("PRECIOUNITARIO") = PRECIOUNITARIO

        'Reset the edit index.
        GridRequisicion.EditIndex = -1

        'Bind data to the GridView control.
        GridRequisicion.DataSource = Session("Requisicion")
        GridRequisicion.DataBind()
    End Sub

    Sub GridRequisicion_RowDeleting(ByVal sender As Object, ByVal e As GridViewDeleteEventArgs)
        Dim dt As DataTable = CType(Session("Requisicion"), DataTable)
        dt.Rows(e.RowIndex).Delete()
        GridRequisicion.DataSource = dt
        GridRequisicion.DataBind()
    End Sub
#End Region

   
    
    
End Class
